package com.nineclock.sign.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.nineclock.sign.mapper.SignMapper;
import com.nineclock.sign.mapper.SignPictureMapper;
import com.nineclock.sign.service.SignService;
import com.nineclock.common.enums.ResponseEnum;
import com.nineclock.common.exception.NcException;
import com.nineclock.common.threadlocal.CurrentUserHolder;
import com.nineclock.common.utils.BeanHelper;
import com.nineclock.sign.dto.SignDTO;
import com.nineclock.sign.pojo.SignInfo;
import com.nineclock.sign.pojo.SignPicture;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class SignServiceImpl  implements SignService {

    @Autowired
    private SignMapper signMapper;
    @Autowired
    private SignPictureMapper signPictureMapper;

    @Override
    public List<SignDTO> queryPageCurrentUserByMonth(String dateStr) {
        LambdaQueryWrapper<SignInfo> signInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        signInfoLambdaQueryWrapper.eq(SignInfo::getCompanyId, CurrentUserHolder.get().getCompanyId());
        signInfoLambdaQueryWrapper.eq(SignInfo::getCompanyUserId,CurrentUserHolder.get().getCompanyUserId());
        signInfoLambdaQueryWrapper.eq(SignInfo::getCreateMonth, "2021-03");
        List<SignInfo> signInfos = signMapper.selectList(signInfoLambdaQueryWrapper);

        if(CollectionUtil.isEmpty(signInfos)){
            throw new NcException(ResponseEnum.SIGN_DATA_NULL);
        }
        Integer mouthCount = signMapper.selectCount(signInfoLambdaQueryWrapper);
        List<SignDTO> signDTOS = BeanHelper.copyWithCollection(signInfos, SignDTO.class);

        for (SignDTO signDTO : signDTOS) {
            signDTO.setUserName(CurrentUserHolder.get().getUsername());
            signDTO.setMonthCount(String.valueOf(mouthCount));
            LambdaQueryWrapper<SignPicture> signPictureLambdaQueryWrapper = new LambdaQueryWrapper<>();
            signPictureLambdaQueryWrapper.eq(SignPicture::getSignId,signDTO.getId());
            List<SignPicture> signPictures = signPictureMapper.selectList(signPictureLambdaQueryWrapper);
            List<String> collect = signPictures.stream().map(new Function<SignPicture, String>() {
                @Override
                public String apply(SignPicture signPicture) {
                    return signPicture.getUrl();

                }
            }).collect(Collectors.toList());
            String join = String.join(",", collect);
             signDTO.setImages(join);
        }

        return signDTOS;
    }

}
